package com.tanhua.recommend.msg;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.recommend.pojo.RecommendVideo;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 下午 21:50 2021/1/11
 * @ModifiedBy:
 */
@Component
@RocketMQMessageListener(topic = "tanhua-video",
        consumerGroup = "tanhua-video-consumer")
@Slf4j
public class VideoMsgConsumer implements RocketMQListener<String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String msg) {
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long userId = jsonNode.get("userId").asLong();
            Long vid = jsonNode.get("vid").asLong();
            Integer type = jsonNode.get("type").asInt();

            //构建对象
            RecommendVideo recommendVideo = new RecommendVideo();
            recommendVideo.setVideoId(vid);
            recommendVideo.setId(ObjectId.get());
            recommendVideo.setUserId(userId);
            recommendVideo.setDate(System.currentTimeMillis());

            switch (type){
                case 1:{
                    recommendVideo.setScore(2d);
                    break;
                }
                case 2:{
                    recommendVideo.setScore(5d);
                    break;
                }
                case 3:{
                    recommendVideo.setScore(-5d);
                    break;
                }
                case 4:{
                    recommendVideo.setScore(10d);
                    break;
                }
                default:{
                    recommendVideo.setScore(0d);
                    break;
                }
            }
            String collectionName = "recommend_video_" + new DateTime().toString("yyyyMMdd");
            this.mongoTemplate.save(recommendVideo, collectionName);
        } catch (Exception e) {
            log.error("处理小视频消息失败~");
        }
    }
}
